using BookApi.Model;
using BookApi.Common;
using Microsoft.AspNetCore.Mvc;
using BookApi.Dto;
using BookApi.Interfaces;
namespace BookApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BookController : ControllerBase
{
    private IRepository<Book> _bookRep;
    public BookController(IRepository<Book> bookRep)
    {
        _bookRep = bookRep;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var list = await _bookRep.GetAllAsync();
        if (list.Count == 0)
        {
            return Ok(ApiResponse<string>.Fail(1004, "暂无数据"));
        }
        return Ok(ApiResponse<List<Book>>.Success(list));
    }

    [HttpPost]
    public async Task<IActionResult> Add(BookDto bookDto)
    {
        var obj = new Book { BookName = bookDto.BookName, Author = bookDto.Author };
        await _bookRep.AddAsync(obj);
        return Ok(ApiResponse<Book>.Success(obj, "新增成功"));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Add(int id, BookDto bookDto)
    {
        var obj = await _bookRep.GetByIdAsync(id);
        if (obj == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此书,修改失败"));
        }
        obj.BookName = bookDto.BookName;
        obj.Author = bookDto.Author;
        await _bookRep.UpdateAsync(obj);
        return Ok(ApiResponse<Book>.Success(obj));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Add(int id)
    {
        var obj = await _bookRep.GetByIdAsync(id);
        if (obj == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此书,删除失败"));
        }
        await _bookRep.DelAsync(obj);
        return Ok(ApiResponse<Book>.Success(obj));
    }

}